using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AutoGear.BLL;
using ECommerce.Library.DataStructure;
using System.Collections.Generic;
using System.IO;
using ECommerce.Library;
using Entity;
using eShop.Model;
using eShop.DataAccess;
using eShop.Business;

public partial class admin_product_category_edit : SiteAdminBasePage
{
    private Category _category;
    public Category Category
    {
        get
        {
            if (_category == null)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["cid"]))
                {
                    int categoryId = 0;
                    if (int.TryParse(Request.QueryString["cid"], out categoryId))
                    {
                        _category = CategoryManager.Load(categoryId);
                    }
                }
            }
            return _category;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindControls();
        }
        uccResponseMessage.Visible = false;
    }

    protected void BindControls()
    {
        LoadProductCategory();
        BindCategoryData(Category);
        BindPartners(Category);
    }

    private void BindPartners(Category category)
    {
        ECommerce.DAL.CustomCollection<Manufacturer> brands = ManufacturerManager.Brands(true);
        cbxPartners.DataSource = brands;
        cbxPartners.DataBind();
        if (category != null)
        {
            ECommerce.DAL.CustomCollection<Manufacturer> probrand = ManufacturerManager.GetByProductCategory(category.CategoryId);
            if (probrand != null) 
            {
                for (int i = 0; i < probrand.Count;i++ )
                {
                    foreach (ListItem li in cbxPartners.Items)
                    {
                        if (probrand[i].ProductBrandId == Convert.ToInt32(li.Value))
                        {
                            li.Selected = true;
                        }
                    }
                }
            }
        }
    }


    private void BindCategoryData(Category category)
    {
        if (category != null)
        {
            tbxCategoryName.Text =Server.HtmlDecode(category.CategoryName);
            tbxDisplayOrder.Text = category.DisplayOrder;
            cbxIsActive.Checked = category.IsActive;
            ddlParent.SelectedValue = category.ParentCategoryId.ToString();
            imgCategoryImage.ImageUrl = ImageResizer.CheckImageMissing(category.CategoryImageUrl, SiteSettings.NoImageLargeThumbnailUrl);
            imgCategoryBannerImage.ImageUrl = ImageResizer.CheckImageMissing(category.CategoryBannerImageUrl, SiteSettings.NoImageLargeThumbnailUrl);
           
        }
    }

    protected void LoadProductCategory()
    {
        ddlParent.Items.Clear();
        ReadWriteCustomCollection<KeyValuePair<string, string>> productCategoryTree = CategoryManager.GetSubCategoryTree(SiteUtility.SuperRootCategoryId);
        foreach (KeyValuePair<string, string> productCategory in productCategoryTree)
        {
            ddlParent.Items.Add(new ListItem(productCategory.Key,Server.HtmlEncode(productCategory.Value)));
        }
    }

    private string UploadLogoTempFile()
    {
        string logoTempFile = null;
        if (fluCategoryLogo.HasFile)
        {
            logoTempFile = SiteUtility.TempFolder + fluCategoryLogo.FileName;
            if (File.Exists(MapPath(logoTempFile)))
                FileAccessUtility.DeleteFile(logoTempFile);

            string logoContentType = fluCategoryLogo.PostedFile.ContentType.ToLower();
            if (logoContentType == "image/jpg" || logoContentType == "image/gif" || logoContentType == "image/png" || logoContentType == "image/x-png"
                || logoContentType == "image/jpeg" || logoContentType == "image/pjpeg" || logoContentType == "image/bmp")
            {
                fluCategoryLogo.SaveAs(MapPath(logoTempFile));
            }
            else
            {
                uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ImageFormateNotSupported);
            }
        }
        return logoTempFile;
    }

    private string UploadBannerTempFile()
    {
        string bannerTempFile = null;
        if (fluCategoryBanner.HasFile)
        {
            bannerTempFile = SiteUtility.TempFolder + fluCategoryBanner.FileName;
            if (File.Exists(MapPath(bannerTempFile)))
                FileAccessUtility.DeleteFile(bannerTempFile);

            string bannerContentType = fluCategoryBanner.PostedFile.ContentType.ToLower();
            if (bannerContentType == "image/jpg" || bannerContentType == "image/gif" || bannerContentType == "image/png" || bannerContentType == "image/x-png"
                   || bannerContentType == "image/jpeg" || bannerContentType == "image/pjpeg" || bannerContentType == "image/bmp")
            {
                fluCategoryBanner.SaveAs(MapPath(bannerTempFile));
            }
            else
            {
                uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ImageFormateNotSupported);
            }
        }
        return bannerTempFile;
    }

    protected void Create_Click(object sender, EventArgs e)
    {
        try
        {
            string logoTempFile = null;
            string categoryTitle = null;
            string bannerTempFile = null;
            if (string.IsNullOrEmpty(tbxCategoryName.Text))
            {
                uccResponseMessage.SetFailMessage(AutoGearCommonMessage.CategoryUpdateFailed);
            }
            else
            {
                categoryTitle = Server.HtmlEncode(tbxCategoryName.Text.Trim());

                logoTempFile = UploadLogoTempFile();
                bannerTempFile = UploadBannerTempFile();

                Category updatedCategory = (Category)CategoryManager.Clone(Category);
                updatedCategory.CategoryName = Security.BindStringInput(Server.HtmlEncode(tbxCategoryName.Text), SecurityLevel.Zero);
                                updatedCategory.CategoryTitle = Security.BindStringInput(Server.HtmlEncode(tbxCategoryName.Text), SecurityLevel.Zero);
                updatedCategory.IsActive = cbxIsActive.Checked;
                updatedCategory.ParentCategoryId = int.Parse(ddlParent.SelectedValue);
                updatedCategory.DisplayOrder = Security.BindStringInput(tbxDisplayOrder.Text, SecurityLevel.Zero);
                updatedCategory = CategoryManager.Update(Category, updatedCategory, CategoryParentChanged(), CategoryNameChanged(), logoTempFile, bannerTempFile);

                if (updatedCategory != null)
                {
                    uccResponseMessage.SetSuccessMessage(AutoGearCommonMessage.CategoryUpdateSuccessful);
                    UpdatePartnerData(updatedCategory);
                    BindControls();
                    BindCategoryData(updatedCategory);
                    
                }
                else
                {
                    uccResponseMessage.SetFailMessage(AutoGearCommonMessage.CategoryUpdateFailed);
                }
            }
        }
        catch (InvalidOperationException ex)
        {
            uccResponseMessage.SetFailMessage(ex.Message);
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.CategoryUpdateFailed);
        }
    }

    private void UpdatePartnerData(Category updatedCategory)
    {
        TblPartnerCategories.DeleteTblPartnerCategoriesByCategoryId(updatedCategory.CategoryId);
        foreach (ListItem li in cbxPartners.Items)
        {
            if (li.Selected == true)
            {
                TblPartnerCategories partnerCategories = new TblPartnerCategories();
                partnerCategories.CategoryId = updatedCategory.CategoryId;
                partnerCategories.PartnerId = Convert.ToInt32(li.Value);
                partnerCategories.Save();
            }
        }
    }

    private bool CategoryParentChanged()
    {
        if (Category.ParentCategoryId.ToString() != ddlParent.SelectedValue)
            return true;
        else
            return false;
    }

    private bool CategoryNameChanged()
    {
        if (Category.CategoryName != tbxCategoryName.Text)
            return true;
        else
            return false;
    }
}
